# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from flask.ext.sqlalchemy import SQLAlchemy
from gis import app
from datetime import datetime

db = SQLAlchemy(app)

def setnone(v):
    if v=='':
        return None
    else:
        return v
def setzero(v):
    if v=='':
        return 0
    else:
        return v

class card(db.Model):
    __tablename__='card'
    card_id = db.Column(db.Integer, primary_key=True)
    card_date = db.Column(db.Date, nullable=False)
    card_dept = db.Column(db.Text, nullable=False)
    card_fibername=db.Column(db.Text, nullable=False)
    card_fibercode=db.Column(db.Text, nullable=False)
    card_count=db.Column(db.Integer, nullable=False)
    card_use=db.Column(db.Text)
    card_action=db.Column(db.Text)
    card_gis=db.Column(db.Boolean)
    card_memo=db.Column(db.Text)
    card_fibercore=db.Column(db.Integer)
    card_fiberlen=db.Column(db.Integer)
    card_source=db.Column(db.Text)
    card_update=db.Column(db.DateTime)
    card_cardprint=db.Column(db.Boolean)
    card_usedate=db.Column(db.Date)
    card_userid=db.Column(db.Integer,db.ForeignKey('user.id'))

    def __init__(self, card_date, card_dept,card_fibername,card_fibercode,card_count,card_use=None,card_action=None,card_gis=False,card_memo=None,card_fibercore=None,card_fiberlen=None,card_source=None,card_cardprint=False,card_usedate=None):
        self.card_date = card_date
        self.card_dept = card_dept
        self.card_fibername=card_fibername
        self.card_fibercode=card_fibercode
        self.card_count=card_count
        self.card_use=card_use
        self.card_action=card_action
        self.card_gis=card_gis
        self.card_memo=card_memo
        self.card_fibercore=card_fibercore
        self.card_fiberlen=card_fiberlen
        self.card_source=card_source
        self.card_update=datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
        self.card_cardprint=card_cardprint
        self.card_usedate=card_usedate

    def __repr__(self):
        return '<card %r:%r>' % (self.card_date,self.card_fibername)


ROLE_USER = 0
ROLE_ADMIN = 1

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    nickname = db.Column(db.String(64), index = True, unique = True)
    email = db.Column(db.String(120), index = True, unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    cards=db.relationship('card',backref='author',lazy='dynamic')

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User %r>' % (self.nickname)
